package com.softserveinc.interactive_board.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.softserveinc.interactive_board.domain.User;
import com.softserveinc.interactive_board.domain.UserType;
import com.softserveinc.interactive_board.service.InteractiveBoardService;

@Controller
@RequestMapping("registration")
public class RegistrationController {

	@RequestMapping(method = RequestMethod.GET)
	public String def() {
		return "redirect:/registration/";
	}

	@RequestMapping(method = RequestMethod.GET, value="/")
	public String def(Model model) {
		model.addAttribute("redirected", false);
		return "redirect:/registration/index";
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/index")
	public String index(@RequestParam("redirected") boolean redirected, Model model) {
		model.addAttribute("userAttr", new User());
		model.addAttribute("redirected", redirected);
		model.addAttribute("userTypesAttr", this.interactiveBoardService.getRegistratebleUserTypes());
		return "registration/index";
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/index")
	public String index(@ModelAttribute("userAttr") User user, Model model) {
		user.setUserType(new UserType(2));
		if (!this.interactiveBoardService.addUser(user)) {
			model.addAttribute("redirected", true);
			return "redirect:/registration/index";
		}
		return "redirect:/";
	}

	private InteractiveBoardService interactiveBoardService;

	@Autowired	
	@Qualifier("interactiveBoardServiceImpl")
	public void setInteractiveBoardService(InteractiveBoardService interactiveBoardService) {
		this.interactiveBoardService = interactiveBoardService;
	}
}
